package com.mojo.concurrent.lock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 重入读写锁示例
 * <p>
 * 重入读写锁是一组锁，包括三个成员变量：sync,读锁，写锁
 * 使用读多写少的场景。读写是互斥的，读-读不互斥，可多个线程同时拥有读锁
 * </p>
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/8/18 10:51
 */
public class ReadAndWriteLock01 {
    ReadWriteLock lock = new ReentrantReadWriteLock();
    private int ticket = 100;

    public void testReadWrite() {
        while (true) {
            lock.writeLock().lock();
            if (ticket > 0) {
                try {
                    Thread.sleep(10);
                    System.out.println(Thread.currentThread().getName() + "买了第" + ticket + "张票");
                    //if (ticket == 50) {
                    //    int n = 1 / 0;
                    //}
                    ticket--;
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                } finally {
                    lock.writeLock().unlock();
                }
                //
            } else {
                lock.writeLock().unlock();
                break;
            }
        }
    }
}

